'''
Desc: 编写一个布局实例
Author: 陈爱国
Date: 2024-08-28 12:10:18
'''
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import sys
import os

# 获得当前文件所在目录
BASE_PATH = os.path.dirname(os.path.realpath(sys.argv[0]))

# 状态映射表
STATUS_MAPPING = {
    0: "初始化中",
    1: "待执行",
    2: "正在执行",
    3: "完成并提醒",
    10: "异常并停止",
    11: "初始化失败"
}

class LayoutDemo(QWidget):
    def __init__(self):
        super().__init__()

        # 控件
        self.goods_input = None

        # 窗体标题        
        self.setWindowTitle("布局实例")

        # 窗体尺寸
        self.resize(1228, 450)

        # 窗体位置
        fg = self.frameGeometry()
        deskCenter = QDesktopWidget().availableGeometry().center()
        fg.moveCenter(deskCenter)

        # 创建界面整体布局 -- 垂直布局
        layout = QVBoxLayout()     

        # 初始化顶部
        layout.addLayout(self.init_header())
        # 初始化商品输入
        layout.addLayout(self.init_goods_add())
        # 初始化表格
        layout.addLayout(self.init_table())
        # 初始化底部
        layout.addLayout(self.init_footer())
        # 增加弹簧
        # layout.addStretch()  # 删除弹簧，则表格充满界面

        # 设置窗体的布局为垂直布局
        self.setLayout(layout)

    def init_header(self):
        """
        初始化顶部
        """
         # ============= 顶部按钮区(开始) ==================
        layout_header = QHBoxLayout()

        # 顶部区域放两个按钮
        start_btn = QPushButton("开始")
        stop_btn = QPushButton("停止")
        layout_header.addWidget(start_btn)
        layout_header.addWidget(stop_btn)
        # 增加弹簧
        layout_header.addStretch()

        return layout_header
    
    def init_goods_add(self):
        """
        初始化商品添加
        """
        layout_goods_add = QHBoxLayout()

        # 输入框
        goods_input = QLineEdit()
        goods_input.setText("B0194WDVHI=100")
        goods_input.setPlaceholderText("请输入商品的ID或名称")
        self.goods_input = goods_input
        layout_goods_add.addWidget(goods_input)

        # 添加按钮
        add_btn = QPushButton("添加")
        # 添加按钮的点击事件
        add_btn.clicked.connect(self.event_add_click)
        layout_goods_add.addWidget(add_btn)

        return layout_goods_add
    
    def init_table(self):
        """
        初始化表格
        """
        layout_table = QHBoxLayout()

        # 创建表格
        self.tableWidget = tableWidget = QTableWidget(0, 8)

        # 设置表格的列
        table_header = [
            {"field":"asin", "text": "ASIN", "width": 120},
            {"field":"title", "text": "标题", "width": 150},
            {"field":"url", "text": "URL", "width": 400},
            {"field":"price", "text": "底价", "width": 100},
            {"field":"success", "text": "成功次数", "width": 100},
            {"field":"error", "text": "503次数", "width": 100},
            {"field":"status", "text": "状态", "width": 100},
            {"field":"frequency", "text": "频率(N秒/次)", "width": 100},
        ]

        for idx, info in enumerate(table_header):
            item = QTableWidgetItem()
            item.setText(info['text'])
            tableWidget.setHorizontalHeaderItem(idx, item)
            tableWidget.setColumnWidth(idx, info['width'])

        # 初始化表格数据
        # 读取数据文件
        import json

        file_path = os.path.join(BASE_PATH, "db", "db.json")
        with open(file_path, mode='r', encoding='utf-8') as f:
            data = f.read()
        data_list = json.loads(data)

        current_row_count = tableWidget.rowCount()  # 当前表格的行数

        for row_list in data_list:
            # 插入一新行
            tableWidget.insertRow(current_row_count)

            # 写入数据
            for i, ele in enumerate(row_list):
                # 状态值与状态文本的转换
                ele = STATUS_MAPPING[ele] if i==6 else ele

                cell = QTableWidgetItem(str(ele))

                # 设置单元格是否可以修改
                if i in [0, 4, 5, 6]:
                    # 设置不可修改
                    cell.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

                tableWidget.setItem(current_row_count, i, cell)

            current_row_count += 1

        # 表格添加到布局中
        layout_table.addWidget(tableWidget)

        return layout_table
    
    def init_footer(self):
        """
        初始化底部
        """
        layout_footer = QHBoxLayout()

        # QLabel
        check_label = QLabel("未检测")
        layout_footer.addWidget(check_label)

        # 增加弹簧
        layout_footer.addStretch()

        # 添加按钮
        btn_reinit = QPushButton("重新初始化")
        layout_footer.addWidget(btn_reinit)

        btn_recheck = QPushButton("重新检测")
        layout_footer.addWidget(btn_recheck)

        btn_setzero = QPushButton("次数清零")
        layout_footer.addWidget(btn_setzero)

        btn_delcheck = QPushButton("删除检测项")
        layout_footer.addWidget(btn_delcheck)

        btn_smtpconf = QPushButton("SMTP报警配置")
        btn_smtpconf.clicked.connect(self.event_smtp_click)
        layout_footer.addWidget(btn_smtpconf)

        btn_proxyip = QPushButton("代理IP")
        layout_footer.addWidget(btn_proxyip)

        return layout_footer

    def event_add_click(self):
        # 1 获取输入框的内容
        input_txt = self.goods_input.text()
        # 去掉输入两边的空格
        input_txt = input_txt.strip()
        # 判断是否为空
        if not input_txt:
            # 消息提示
            QMessageBox.warning(self, "错误", "商品ASIN输入错误")
            return
        # 获取商品和价格
        asin, price = input_txt.split("=")
        price = float(price)

        # 2 添加到表格
        new_row_list = [asin, '', '', price, 0, 0, 0, 5]

        current_row_count = self.tableWidget.rowCount()  # 当前表格的行数
        # 插入一新行
        self.tableWidget.insertRow(current_row_count)

        # 写入数据
        for i, ele in enumerate(new_row_list):
            # 状态值与状态文本的转换
            ele = STATUS_MAPPING[ele] if i==6 else ele

            cell = QTableWidgetItem(str(ele))

            # 设置单元格是否可以修改
            if i in [0, 4, 5, 6]:
                # 设置不可修改
                cell.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

            self.tableWidget.setItem(current_row_count, i, cell)

        # 3 通过爬虫获取标题等信息
        from threads import NewTaskThread
        thread = NewTaskThread(current_row_count, self)
        thread.success.connect(self.init_task_success_callback)
        thread.error.connect(self.init_task_error_callback)
        thread.start()

    def init_task_success_callback(self, index, asin, title, url):
        print(index, asin, title, url)

    def init_task_error_callback(self, index, asin, title, url):
        print(index, asin, title, url)

    def event_smtp_click(self):
        from utils.dialog import AlertDialog
        dialog = AlertDialog()
        dialog.setWindowModality(Qt.ApplicationModal)
        dialog.exec_()


if __name__ == '__main__':
    app = QApplication(sys.argv)

    win = LayoutDemo()
    win.show()

    sys.exit(app.exec_())